<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-form-item label="员工编号" prop="employeeNumber">
          <el-input
            v-model="queryParams.employeeNumber"
            placeholder="请输入员工编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="门店" prop="storeId">
          <el-select v-model="queryParams.storeId" placeholder="请选择门店" clearable>
            <el-option
              v-for="dict in storeList"
              :key="dict.value"
              :label="dict.name"
              :value="dict.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mt20">

      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"><span style="font-size: large">员工信息</span></el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['wms:employees:add']"
          >新增
          </el-button>
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['wms:employees:export']"
          >导出
          </el-button>
        </el-col>
      </el-row>

      <el-table v-loading="loading" :data="employeesList" border class="mt20">
        <el-table-column label="用户" prop="userId">
          <template #default="scope">
            <span>{{ getUserInfoNameById(scope.row.userId).nickName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="门店" prop="storeId">
          <template #default="scope">
            <span>{{ getNameById(scope.row.storeId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="员工编号" prop="employeeNumber"/>
        <el-table-column label="姓名" prop="name"/>
        <el-table-column label="性别 " prop="gender">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.gender"/>
          </template>
        </el-table-column>
        <el-table-column label="工号" prop="workNumber"/>
        <el-table-column label="出生年月" align="center" prop="birthDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="身份证号" prop="idCardNumber"/>
        <el-table-column label="联系电话" prop="phoneNumber"/>
        <el-table-column label="电子邮箱" prop="email"/>
        <el-table-column label="家庭地址" prop="homeAddress"/>
        <el-table-column label="岗位" prop="positionId">
          <template #default="scope">
            <span>{{ getPostNameById(scope.row.positionId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入职日期" align="center" prop="joinDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.joinDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="离职日期" align="center" prop="leaveDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.leaveDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="月薪" prop="monthlySalary"/>
        <el-table-column label="银行账号" prop="bankAccount"/>
        <el-table-column label="学历" prop="education">
          <template #default="scope">
            <dict-tag :options="degree" :value="scope.row.education"/>
          </template>
        </el-table-column>
        <el-table-column label="工作经验" prop="workExperience"/>
        <el-table-column label="照片路径" align="center" prop="photoPath" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.photoPath" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createBy"/>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改人" prop="updateBy"/>
        <el-table-column label="备注" prop="remarks"/>
        <el-table-column label="操作" align="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['wms:employees:edit']">修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['wms:employees:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-row>
        <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-row>

    </el-card>
    <!-- 添加或修改员工信息对话框 -->
    <el-drawer :title="title" v-model="open" size="50%" append-to-body>
      <el-form ref="employeesRef" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择用户" clearable>
            <el-option
              v-for="dict in userList"
              :key="dict.value"
              :label="dict.nickName"
              :value="dict.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="门店" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择门店" clearable>
            <el-option
              v-for="dict in storeList"
              :key="dict.value"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="员工编号" prop="employeeNumber">
          <el-input v-model="form.employeeNumber" placeholder="请输入员工编号"/>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="性别 " prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="工号" prop="workNumber">
          <el-input v-model="form.workNumber" placeholder="请输入工号"/>
        </el-form-item>
        <el-form-item label="岗位" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择岗位" clearable>
            <el-option
              v-for="dict in postList"
              :key="dict.value"
              :label="dict.postName"
              :value="dict.postId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出生年月" prop="birthDate">
          <el-date-picker clearable
                          v-model="form.birthDate"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择出生年月">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNumber">
          <el-input v-model="form.idCardNumber" placeholder="请输入身份证号"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱"/>
        </el-form-item>
        <el-form-item label="家庭地址" prop="homeAddress">
          <el-input v-model="form.homeAddress" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="入职日期" prop="joinDate">
          <el-date-picker clearable
                          v-model="form.joinDate"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择入职日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="离职日期" prop="leaveDate">
          <el-date-picker clearable
                          v-model="form.leaveDate"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择离职日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="月薪" prop="monthlySalary">
          <el-input v-model="form.monthlySalary" placeholder="请输入月薪"/>
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="form.bankAccount" placeholder="请输入银行账号"/>
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-select v-model="form.education" placeholder="请选择学历">
            <el-option
              v-for="dict in degree"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工作经验" prop="workExperience">
          <el-input v-model="form.workExperience" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="照片路径" prop="photoPath">
          <image-upload v-model="form.photoPath"/>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Employees">
import {addEmployees, delEmployees, getEmployees, listEmployees, updateEmployees} from "@/api/wms/employees";
import {getStoreNameAndId} from "@/api/wms/storeInformation";
import {toRefs} from "vue";
import {getPostName} from "@/api/system/post";
import {getUserInfo} from "@/api/system/user";
import {listByIds} from "@/api/system/oss";

const {proxy} = getCurrentInstance();
const {degree, sys_user_sex, sys_normal_disable} = proxy.useDict('degree', 'sys_user_sex', 'sys_normal_disable');

const employeesList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const storeList = ref([]);
const userList = ref([]);
const postList = ref([]);
const imgUrl = ref("");
const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      storeId: undefined,
      employeeNumber: undefined,
      name: undefined,
      positionId: undefined,
    },
    rules: {
      id: [
        {required: true, message: "id不能为空", trigger: "blur"}
      ],
      userId: [
        {required: true, message: "用户不能为空", trigger: "change"}
      ],
      storeId: [
        {required: true, message: "所属门店不能为空", trigger: "change"}
      ],
      name: [
        {required: true, message: "姓名不能为空", trigger: "blur"},
        {
          min: 2,
          max: 20,
          message: "姓名必须在2-20位之间",
          trigger: "blur"
        }
      ],
      gender: [
        {required: true, message: "性别 不能为空", trigger: "change"}
      ],
      birthDate: [
        {required: true, message: "出生年月不能为空", trigger: "blur"}
      ],
      positionId: [
        {required: true, message: "岗位不能为空", trigger: "change"}
      ],
      phoneNumber: [{
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号格式',
        trigger: 'blur'
      }],
      email: [{
        pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
        message: '请输入正确的邮箱格式',
        trigger: 'blur'
      }],
      idCardNumber: [{
        pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
        message: '请输入正确的身份证号格式',
        trigger: 'blur'
      }],
      bankAccount: [{
        pattern: /^([1-9]{1})(\d{14}|\d{18})$/,
        message: '请输入正确的银行卡号格式',
        trigger: 'blur'
      }],
      monthlySalary: [{
        pattern: /^([1-9]\d{0,7}|0)(\.\d{1,2})?$/,
        message: '请输入正确的月工资格式',
        trigger: 'blur'
      }],
      joinDate: [
        {required: true, message: "入职日期不能为空", trigger: "blur"}
      ],
      status: [
        {required: true, message: "状态不能为空", trigger: "change"}
      ],
      createTime: [
        {required: true, message: "创建时间不能为空", trigger: "blur"}
      ],
      updateTime: [
        {required: true, message: "修改时间不能为空", trigger: "blur"}
      ],
    }
  })
;

const {queryParams, form, rules} = toRefs(data);

//获取图片地址

//获取门店列表
getStoreNameAndId().then(res => {
  storeList.value = res.data;
});


//获取用户列表
getUserInfo().then(res => {
  userList.value = res.data;
});

function getUserInfoNameById(userId) {
  return userList.value.find(item => item.userId === userId);
}

//获取岗位列表
getPostName().then(res => {
  postList.value = res.data
})

//根据id获取岗位名称
function getPostNameById(postId) {
  return postList.value.find(item => item.postId === postId).postName;
}

//根据id获取名称
function getNameById(id) {
  return storeList.value.find(item => item.id === id).name;
}

/** 查询员工信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listEmployees(queryParams.value).then(response => {
    employeesList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    storeId: null,
    employeeNumber: null,
    name: null,
    gender: null,
    workNumber: null,
    birthDate: null,
    idCardNumber: null,
    phoneNumber: null,
    email: null,
    homeAddress: null,
    positionId: null,
    joinDate: null,
    leaveDate: null,
    status: null,
    monthlySalary: null,
    bankAccount: null,
    education: null,
    workExperience: null,
    photoPath: null,
    createBy: null,
    createTime: null,
    updateTime: null,
    updateBy: null,
    remarks: null
  };
  proxy.resetForm("employeesRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加员工信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getEmployees(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改员工信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["employeesRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateEmployees(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addEmployees(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除员工信息编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delEmployees(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wms/employees/export', {
    ...queryParams.value
  }, `employees_${new Date().getTime()}.xlsx`)
}

getList();
</script>
